package com.zh

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.awt.ComposeWindow
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.application
import com.zh.filetransport.chat.CreateChatService
import com.zh.filetransport.contrl.CommandOpen
import com.zh.filetransport.core.NewFileService
import com.zh.filetransport.model.Mode
import com.zh.view.AppLayoutScene
import com.zh.view.ChatMsg
import com.zh.view.FileDataItem
import com.zh.view.data.ChatStore
import com.zh.view.data.ReceiveTaskStore

@Composable
@Preview
fun App(window: ComposeWindow) {
    //设置主题颜色
    MaterialTheme(
        colorScheme = lightColorScheme()
    ) {
        AppLayoutScene(window)
    }
}


fun main() = application {
    val mode = Mode.UI.name
    val fileService = remember { NewFileService(8181, mode) }
    val chatService = remember { CreateChatService(8183) }

    LaunchedEffect(Unit) {
        //启动服务
        fileService.start { it ->
            val task = FileDataItem(it.id, it.filePath, it.totalSize, it.isDir)
//            println("add receive task : $task")
            ReceiveTaskStore.addItem(task)
        }

        CommandOpen("127.0.0.1")//默认为本地IP
        chatService.start { it ->
//            println("收到来自[${it.second}]的消息: ${it.first}")
            val chatMsg = ChatMsg(System.currentTimeMillis().toString(), it.first, false, it.second)
            ChatStore.addToList(chatMsg)
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            // 服务清理
            fileService.shutdown()
            chatService.shutdown()
        }
    }

    Window(
        onCloseRequest = ::exitApplication,
        title = "FileTransport",
        //设置窗口大小，并居中
        state = WindowState(size = DpSize(1080.dp, 720.dp), position = WindowPosition(alignment = Alignment.Center)),
    ) {
        App(window)
    }
}